<template>
  <div style="padding: 45px 20px">
    <div style="margin-bottom: 15px">
      <el-input
        v-model="params.name"
        style="width: 200px; font-size: 1em"
        placeholder="请输入姓名"
      ></el-input>
      <el-input
        v-model="params.phone"
        style="width: 200px; margin-left: 5px; font-size: 1em"
        placeholder="请输入电话"
      ></el-input>
      <el-button
        style="margin-left: 10px; font-size: 1em"
        @click="findBySearch()"
        >查询</el-button
      >
      <el-button style="margin-left: 10px; font-size: 1em" @click="reset()"
        >清空</el-button
      >
      <el-button style="margin-left: 10px; font-size: 1em" @click="add()"
        >新增</el-button
      >
      <div style="float: right; color: gray">在线用户({{ userslength }})</div>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%; font-size: 1em">
        <el-table-column label="头像">
          <template v-slot="scope">
            <el-image
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
              style="width: 50px; height: 50px; border-radius: 50%"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <span type="primary" @click="edit(scope.row)">
              <i
                class="iconfont icon-bianji"
                style="font-size: 25px; color: #007bff"
              ></i>
            </span>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <span slot="reference" type="danger"><i
                class="iconfont icon-shanchu"
                style="font-size: 25px; color: #007bff"
              ></i></span>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNum"
        :page-sizes="5"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
        title="请填写信息"
        :visible.sync="dialogFormVisible"
        width="30%"
      >
        <el-form :model="form">
          <el-form-item label="姓名" label-width="15%">
            <el-input
              v-model="form.name"
              autocomplete="off"
              style="width: 90%"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="15%">
            <el-radio v-model="form.sex" label="男">男</el-radio>
            <el-radio v-model="form.sex" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="年龄" label-width="15%">
            <el-input
              v-model="form.age"
              autocomplete="off"
              style="width: 90%"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" label-width="15%">
            <el-input
              v-model="form.phone"
              autocomplete="off"
              style="width: 90%"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" label-width="15%">
            <el-select
              v-model="form.role"
              placeholder="请选择"
              style="width: 90%"
            >
              <el-option label="管理员" value="ADMIN"></el-option>
              <el-option label="用户" value="STUDENT"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

let client
export default {
  data() {
    return {
      params: {
        name: "",
        phone: "",
        pageNum: 1,
        pageSize: 5,
      },
      tableData: [],
      total: 0,
      dialogFormVisible: false,
      form: {},
      userslength: 0,
    };
  },
  // 页面加载的时候，做一些事情，在created里面
  created() {
    this.findBySearch();
    this.user = JSON.parse(localStorage.getItem('user') || "{}")

    let name = window.btoa(encodeURI(this.user.name))
    let avatar = window.btoa(encodeURI(this.user.avatar))

    client = new WebSocket(`ws://localhost:8080/imserver/${name}/${avatar}`)
    client.onopen = () => {
      console.log('websocket open')
    }
    client.onclose = () => {  // 页面刷新的时候和后台websocket服务关闭的时候
      console.log('websocket close')
    }
    client.onmessage = (msg) => {
      if (msg.data) {
        let json = JSON.parse(msg.data)
        console.log("---------------",json);

        if (json.users && json.users.length) {
          this.userslength = json.users.length;
          console.log('onmessage', this.users);
        }
      }
      client.close()
    }
  },
  beforeDestroy() {
    if (this.client) {
      this.client.close();
      console.log("WebSocket 连接已关闭");
    }
  },
  // 定义一些页面上控件出发的事件调用的方法
  methods: {
    findBySearch() {
      request
        .get("/user/search", {
          params: this.params,
        })
        .then((res) => {
          if (res.code === "0") {
            this.tableData = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message({
              message: res.msg,
              type: "success",
            });
          }
        });
    },
    add() {
      this.form = {};
      this.dialogFormVisible = true;
    },
    edit(obj) {
      this.form = obj;
      this.dialogFormVisible = true;
    },
    reset() {
      this.params = {
        pageNum: 1,
        pageSize: 5,
        name: "",
        phone: "",
      };
      this.findBySearch();
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.findBySearch();
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum;
      this.findBySearch();
    },
    submit() {
      request.post("/user", this.form).then((res) => {
        if (res.code === "0") {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.findBySearch();
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    del(id) {
      request.delete("/user/" + id).then((res) => {
        if (res.code === "0") {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.findBySearch();
        } else {
          this.$message({
            message: res.msg,
            type: "success",
          });
        }
      });
    },
  },
};
</script>
